package com.edu.tool.bc;

import com.edu.tool.bean.Record;
import org.apache.ibatis.jdbc.SQL;

import java.util.*;


public class SysBCSqlProvider {

    public String query(Map<String,Object> fieldValMap){
//        SysBusComp busComp = (SysBusComp)fieldValMap.get("buscomp");
//        fieldValMap.remove("buscomp");
//
//        SysBcDef bcdef = busComp.bcdef;
//
//
//        Set<String> conditionTables = new HashSet<>();
//        Set<String> activeFields    = (Set)fieldValMap.get("activeFields");
//
//        fieldValMap.remove("activeFields");
//
//
//        StringBuffer whereClause = new StringBuffer();
//        whereClause.append(" where ");
//
//
//        Map<String,String> fielddefs     = bcdef.fields;
//        Map<String,String> bean2TableMap = bcdef.bean2Table;
//
//        boolean bFirst = true;
//
//        for (Map.Entry<String,Object> entry : fieldValMap.entrySet()){
//            String fieldName = entry.getKey();
//
//            String beanField = fielddefs.get(fieldName);
//            String bfarray[] = beanField.split("\\.");
//
//
//            if(bFirst){
//                bFirst = false;
//            }
//            else
//            {
//                whereClause.append(" and ");
//            }
//
//            if(bfarray.length == 1){
//                conditionTables.add(bean2TableMap.get(bcdef.baseBean));
//
//                whereClause.append(bcdef.baseBean);
//                whereClause.append(".");
//                whereClause.append(beanField);
//                whereClause.append(" = #{");
//                whereClause.append(fieldName);
//                whereClause.append("}");
//
//
//            }
//            else{
//                conditionTables.add(bean2TableMap.get(bfarray[0]));
//
//                whereClause.append(beanField);
//                whereClause.append(" = #{");
//                whereClause.append(fieldName);
//                whereClause.append("}");
//            }
//        }
//
//        //Set<String> activeTables = new HashSet< >();
//        for (String fieldName:activeFields) {
//            String beanField = fielddefs.get(fieldName);
//            String bfarray[] = beanField.split("\\.");
//
//            if(bfarray.length == 1){
//                conditionTables.add(bean2TableMap.get(bcdef.baseBean));
//            }
//            else{
//                conditionTables.add(bean2TableMap.get(bfarray[0]));
//            }
//        }
//
//
//        Map<String,List<String>>  beanDepson        = SysBusComp.beanDepson;
//        Map<String,List<SysJoinDef>>  bean2JoinDef  = SysBusComp.fromBean2JoinDef;
////        List<SysJoinDef>  joindefs     = bcdef.joindefs;
////
////
////        for (int i = 0; i < joindefs.size(); i++){
////            SysJoinDef joinDef           = joindefs.get(i);
////            String childBean             = joinDef.getChildBean();
////            String parentBean            = joinDef.getParentBean();
////
////
////            List<String> lstBeans        = beanDepson.get(parentBean);
////
////
////            if(lstBeans != null){
////                lstBeans.add(childBean);
////            }else{
////                lstBeans = new ArrayList<>();
////                lstBeans.add(childBean);
////            }
////            beanDepson.put(parentBean,lstBeans);
////
////            List<SysJoinDef> lstJoinDefs = bean2JoinDef.get(parentBean);
////            if(lstJoinDefs != null){
////                lstJoinDefs.add(joinDef);
////            }else{
////                lstJoinDefs = new ArrayList<>();
////                lstJoinDefs.add(joinDef);
////            }
////            bean2JoinDef.put(parentBean,lstJoinDefs);
////        }
//
//        //join tables from base table:
//
//        Queue<String> queue = new LinkedList<String>();
//        queue.add(bcdef.baseBean);
//        StringBuffer JoinClause = new StringBuffer();
//        String baseTable        = bean2TableMap.get(bcdef.baseBean);
//        JoinClause.append(" from ");
//        JoinClause.append(baseTable);
//        JoinClause.append(" ");
//        JoinClause.append(bcdef.baseBean);
//        while (!queue.isEmpty())
//        {
//            String currentBean   = queue.poll();
//
//            List<SysJoinDef> joinDefList = bean2JoinDef.get(currentBean);
//
//            if(joinDefList != null) {
//                for (int i = 0; i < joinDefList.size(); i++) {
//                    SysJoinDef joinDef = joinDefList.get(i);
//                    String childBean = joinDef.getChildBean();
//                    String childTable = bean2TableMap.get(childBean);
//
//                    String childCol = joinDef.getChildField();
//                    String parentCol = joinDef.getParentField();
//
//                    JoinClause.append(" join ");
//                    JoinClause.append(childTable);
//                    JoinClause.append(" ");
//                    JoinClause.append(childBean);
//
//                    JoinClause.append(" on ");
//                    JoinClause.append(currentBean);
//                    JoinClause.append(".");
//                    JoinClause.append(parentCol);
//                    JoinClause.append("=");
//                    JoinClause.append(childBean);
//                    JoinClause.append(".");
//                    JoinClause.append(childCol);
//                }
//
//                List<String> nextBeans = beanDepson.get(currentBean);
//                if (nextBeans != null) {
//                    for (int i = 0; i < nextBeans.size(); i++) {
//                        queue.add(nextBeans.get(i));
//                    }
//                }
//            }
//        }
//
//        StringBuffer selectClause = new StringBuffer();
//        selectClause.append("select ");
//        selectClause.append(bcdef.baseBean);
//        selectClause.append(".");
//        selectClause.append("id");
//        selectClause.append(" as ");
//        selectClause.append(" id ");
//
//        bFirst = false;
//        for(String af: activeFields){
//            String beanField = fielddefs.get(af);
//            String bfarray[] = beanField.split("\\.");
//
//            if(bFirst){
//                bFirst = false;
//            }
//            else{
//                selectClause.append(",");
//            }
//
//            if(bfarray.length == 1){
//                selectClause.append(bcdef.baseBean);
//                selectClause.append(".");
//                selectClause.append(beanField);
//                selectClause.append(" as ");
//                selectClause.append(af);
//            }
//            else{
//                selectClause.append(beanField);
//                selectClause.append(" as ");
//                selectClause.append(af);
//            }
//        }
//
//        selectClause.append(" ").append(JoinClause).append(whereClause);
//
//        String sql = selectClause.toString();
         String sql = (String)fieldValMap.get("querySql");
         fieldValMap.remove("querySql");
        return sql;
    }

    public String update(Map<String,Object> busComp){
        String sql = buildUpdateSql(busComp);
        return sql;

    }

    public String insert(Record record){

        //generate sqls for each entry in Table2ColVal
        StringBuffer sql = new StringBuffer();
        sql.append("insert into s_party(create_time,create_by,update_time,update_by,partyTypeCd,partyUID,name) values(");
        sql.append("#{create_time},#{create_by},#{update_time},#{update_by},#{partyTypeCd},#{partyUID},#{name})");
        return sql.toString();

    }

    public String insert2(Map<String,Object> record){

        String sql =  buildInsertSql(record);
        return sql;

    }

    public String delete(Map<String,Object> record){

        String deleteSql = (String) record.get("deleteSql");
        record.remove("deleteSql");
        return deleteSql;

    }

    private String buildInsertSql(Map<String,Object> record){
        String table = (String)record.get("table");
        record.remove("table");

        return new SQL() {{
            INSERT_INTO(table);
            for( Map.Entry<String,Object> entry:record.entrySet()){
                String  key = entry.getKey();
                if(!key.equalsIgnoreCase("table")) {
                    StringBuffer val = new StringBuffer();
                    val.append("#{");
                    val.append(key);
                    val.append("}");
                    VALUES(key, val.toString());
                }
            }

        }}.toString();
    }

    private String buildUpdateSql(Map<String,Object> record){
        String table = (String)record.get("table");
        record.remove("table");
        Map<String,Object> condition = (Map<String,Object>) record.get("condition");
        record.remove("condition");

        return new SQL() {{
            UPDATE(table);

            for( Map.Entry<String,Object> entry:record.entrySet()){
                String  key = entry.getKey();
                if(!key.equalsIgnoreCase("id")) {

                    StringBuffer setpair = new StringBuffer();
                    setpair.append(key);
                    setpair.append("=");
                    setpair.append("#{");
                    setpair.append(key);
                    setpair.append("}");
                    SET(setpair.toString());
                }
            }

            for( Map.Entry<String,Object> entry:condition.entrySet()){
                String  key = entry.getKey();

                StringBuffer wherepair = new StringBuffer();
                wherepair.append(key);
                wherepair.append("=");
                wherepair.append("#{");
                wherepair.append(key);
                wherepair.append("}");
                WHERE(wherepair.toString());
            }



        }}.toString();
    }

    private String buildSql(Map.Entry<String,List<SysColVal>> table2ColVaList) {

        StringBuffer cols = new StringBuffer();
        StringBuffer vals = new StringBuffer();
        List<SysColVal> colValList = table2ColVaList.getValue();
        for (int j = 0; j < colValList.size(); j++) {
            if(j > 0){
                cols.append(",");
                vals.append(",");
            }
            SysColVal sysColVal = colValList.get(j);
            cols.append(sysColVal.ColName);
            vals.append(sysColVal.Val);
        }

        return new SQL()
                .INSERT_INTO(table2ColVaList.getKey())
                .INTO_COLUMNS(cols.toString())
                .INTO_VALUES(vals.toString())
                .toString();

    }
}